<template>
    <div class="dataBillTable">
      <div class="titleCtn">
        <h1 class="float-l"> 账单管理 </h1>
        <div class="float-r">
          <el-input
            placeholder="模糊搜索描述和备注"
            prefix-icon="el-icon-search"
            v-model="searchDetail"
            style="width:200px;margin-right:5px;"
            @change="getBillList">
          </el-input>
          <el-date-picker
            v-model="searchTime"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            style="width:250px;margin-right:5px;"
            @change="getBillList">
          </el-date-picker>
          <el-button type="primary" @click="addNewBill" class="addBillBtn">新增</el-button>
        </div>
      </div>
      <div class="tableDiv">
        <el-table :data="tableData" border height="100%">
          <el-table-column label="消费用户" >
            <template slot-scope="scope">
                <el-select v-model="scope.row.user" placeholder="请选择" v-if="scope.row.isEdit">
                  <el-option
                    v-for="(item,index) in userOptions"
                    :key="index"
                    :label="item"
                    :value="item">
                  </el-option>
                </el-select>
              <span v-else>{{scope.row.user}}</span>
            </template>
          </el-table-column>
          <el-table-column label="消费金额">
            <template slot-scope="scope">
              <el-input placeholder="请输入内容" v-model="scope.row.amount" v-if="scope.row.isEdit" @input="numFilter(scope.row)"></el-input>
              <span v-else>{{scope.row.amount}}</span>
            </template>
          </el-table-column>
          <el-table-column label="描述" min-width="100">
            <template slot-scope="scope">
              <el-input type="textarea" :rows="1" placeholder="请输入内容" v-model="scope.row.description" v-if="scope.row.isEdit">
              </el-input>
              <span v-else>{{scope.row.description}}</span>
            </template>
          </el-table-column>
          <el-table-column  label="支付类型" >
            <template #header>
              <el-dropdown @command="v => selPaymentType(v)" trigger="click">
                <span class="el-dropdown-link">
                  支付类型<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="">全部</el-dropdown-item>
                  <el-dropdown-item 
                    v-for="item in paymentTypeOptions" 
                    :key="item.id" 
                    :command="item.id">
                    {{item.type}}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
            <template slot-scope="scope">
              <el-select v-model="scope.row.paymentType" placeholder="请选择" v-if="scope.row.isEdit">
                <el-option
                  v-for="item in paymentTypeOptions"
                  :key="item.id"
                  :label="item.type"
                  :value="item.id">
                </el-option>
              </el-select>
              <span v-else>{{scope.row.paymentType | paymentFilter(paymentTypeOptions)}}</span>
            </template>
          </el-table-column>
          <el-table-column label="消费类型">
            <template #header>
              <el-dropdown @command="v => selConsumerType(v)" trigger="click">
                <span class="el-dropdown-link">
                  消费类型<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="">全部</el-dropdown-item>
                  <el-dropdown-item 
                    v-for="item in consumerTypeOptions" 
                    :key="item.id" 
                    :command="item.id">
                    {{item.type}}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
            <template slot-scope="scope">
              <el-select v-model="scope.row.consumerType" placeholder="请选择" v-if="scope.row.isEdit">
                <el-option
                  v-for="item in consumerTypeOptions"
                  :key="item.id"
                  :label="item.type"
                  :value="item.id">
                </el-option>
              </el-select>
              <span v-else>{{scope.row.consumerType | consumerFilter(consumerTypeOptions)}}</span>
            </template>
          </el-table-column>
          <el-table-column label="消费时间" min-width="95">
            <template slot-scope="scope">
              <el-date-picker 
              type="date" 
              style="width:100%"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"  
              v-model="scope.row.time" 
              v-if="scope.row.isEdit">
              </el-date-picker>
              <span v-else>{{scope.row.time | timeFormater}}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注">
            <template slot-scope="scope">
              <el-input type="textarea" :rows="1" placeholder="请输入备注" v-model="scope.row.remark" v-if="scope.row.isEdit">
              </el-input>
              <span v-else>{{scope.row.remark}}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <div v-if="scope.row.isEdit">
                <el-button type="text" size="small" @click="cancleTable(scope.row)">取消</el-button>
                <el-button type="text" size="small" @click="confirmTable(scope.row)">确定</el-button>
              </div>
              <div v-else>
                <el-button type="text" size="small" @click="editTable(scope.row)">编辑</el-button>
                <el-button type="text" size="small" @click="copyTable(scope.row)">复制</el-button>
                <el-button  type="text" size="small" @click="delTable(scope.row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        @size-change="onSizeChange"
        @current-change="onCurrentChange"
        :current-page="currentPage"
        :total="grideTotal"
        :page-size="pageSize"
        :page-sizes="[10, 15, 20, 25]"
        layout="total, prev, pager, next, sizes">
      </el-pagination>
    </div>
</template>
<script>
import axios from "axios"
import moment from "moment"

export default {
  name:"dataBillTable",
  components: {},
  props:{},
  data(){
    return {
      tableData:[],
      // 消费类型
      consumerTypeOptions:[],
      // 消费用户
      userOptions:["小马","驴子"],
      // 支付类型
      paymentTypeOptions:[],
      currentPage:1,
      pageSize:10,
      grideTotal:0,
      // 表头筛选 支付类型
      searchPayment:"",
      // 表头筛选 消费类型
      searchCustom:"",
      // 筛选 描述和备注框模糊搜索
      searchDetail: "",
      searchTime: "",
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
    }
  },
  mounted() {
    // 获取账单列表
    this.getBillList()
    // 获取消费类型列表
    this.getCustomer()
    // 获取支付类型列表
    this.getpayment()
  },
  computed:{
    paymentTypeFilters (){
      return this.paymentTypeOptions.map(item => {
        return {
          text:item.type,
          value:item.id
        }
      })
    }
  },
  filters:{
    consumerFilter(data,consumerTypeOptions){
      let aa = "--"
      consumerTypeOptions.forEach(item => {
        if (item.id === data) {
          aa = item.type
        }
      })
      return aa;
    },
    paymentFilter(data,paymentTypeOptions){
      let aa = "--"
      paymentTypeOptions.forEach(item => {
        if (item.id === data) {
          aa = item.type
        }
      })
      return aa;
    },
    timeFormater(data){
      return moment(data).format("YYYY-MM-DD")
    }
  },
  methods:{
    // 获取消费类型列表
    getCustomer(){
      const that = this;
      axios.get('/consumer/list')
      .then(function ({data}) {
        if (data.code === 200 && data.data) {
          that.consumerTypeOptions = data.data
        }
      })
      .catch(function (error) {
        console.log(error);
      });
    },
    // 获取支付类型列表
    getpayment(){
      const that = this;
      axios.get('/payment/list')
      .then(function ({data}) {
        if (data.code === 200 && data.data) {
          that.paymentTypeOptions = data.data
        }
      })
      .catch(function (error) {
        console.log(error);
      });
    },
    // 获取账单列表
    getBillList(){
      const that = this
      axios.get('/consumer/detail/page/list',{
        params:{
          page: that.currentPage,
          size: that.pageSize,
          paymentType: that.searchPayment,
          consumerType: that.searchCustom,
          description: that.searchDetail,
          time: that.searchTime
        }
      })
      .then(function (response) {
        const data = response.data
        if (data.code === 200) {
          that.tableData =data.data.records.map(item => {
            return {
              ...item,
              isEdit: false
            }
          });
          that.grideTotal = data.data.total || 0;
        }
      })
      .catch(function (error) {
        console.log(error);
      });
    },
    onSizeChange(size){
      this.currentPage = 1;
      this.pageSize = size;
      // 刷新列表
      this.getBillList()
    },
    onCurrentChange(page){
      this.currentPage = page;
      // 刷新列表
      this.getBillList()
    },
    // 添加一行
    addNewBill(){
      const newBill = {
        user: "",
        amount: 0,
        description: "",
        paymentType: "",
        consumerType: "",
        time: "",
        remark: "",
        isEdit: true
      }
      this.tableData.unshift(newBill)
    },
    // 编辑列表
    editTable(row){
      row.isEdit = true;
    },
    // 删除一行
    delTable(row){
      this.$confirm('确认删除此条记录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const that = this;
        axios.post("/consumer/detail/delete/" + row.id)
        .then(function ({data}) {
          if (data && data.code === 200) {
            that.$message({ type: 'success', message: '删除成功'});
            that.getBillList()
          } else {
            that.$message({ type: 'success', message: '删除失败'});
          }
        })
        .catch(function (error) {
          that.$message({ type: 'success', message: '接口报错'});
          console.log(error);
        });
      })
    },
    // 复制一行
    copyTable(row){
       const newBill = {
        user: row.user,
        amount: row.amount || 0,
        description: row.description || "",
        paymentType: row.paymentType || "",
        consumerType: row.consumerType || "",
        time: row.time || "",
        remark: row.remark || "",
        isEdit: true
      }
      this.tableData.unshift(newBill)
    },
    // 编辑状态--取消按钮
    cancleTable(row){
      this.getBillList()
    },
    // 编辑状态--确定按钮
    confirmTable(row){
      // 判断必填
      if (!row.user) {
        this.$message({ message: '消费用户是必填项哦', type: 'warning'});
        return;
      }
      if (!row.amount) {
        this.$message({ message: '消费金额是必填项哦', type: 'warning'});
        return;
      }
      if (!row.description) {
        this.$message({ message: '描述是必填项哦', type: 'warning'});
        return;
      }
      if (!row.paymentType) {
        this.$message({ message: '支付类型是必填项哦', type: 'warning'});
        return;
      }
      if (!row.consumerType) {
        this.$message({ message: '消费类型是必填项哦', type: 'warning'});
        return;
      }
      if (!row.time) {
        this.$message({ message: '消费时间是必填项哦', type: 'warning'});
        return;
      }
      const that =this;
      // 校验完成 发请求新增or修改
      axios.post('/consumer/detail/create', row)
      .then(function (res) {
        if (res.data && res.data.code === 200) {
          that.$message({ message: '操作成功', type: 'success'});
          // 刷新列表
          that.getBillList()
        }
      })
      .catch(function (error) {
        that.$message.error('操作失败');
      });
    },
    // 消费金额输入框 输入限制
    numFilter(row){
      let value = row.amount;
      value = value.replace(/[^\d.]/g,""); //清除"数字"和"."以外的字符
      value = value.replace(/^\./g,""); //验证第一个字符是数字
      value = value.replace(/(\.)\1+/g,'$1'); //只保留第一个., 清除多余的.
      row.amount = value;
    },
    // 表头筛选功能 支付类型
    selPaymentType(value){
      this.searchPayment = value;
      // 刷新列表
      this.getBillList()
    },
    selConsumerType(value){
      this.searchCustom = value;
      // 刷新列表
      this.getBillList()
    }
  }

}
</script>
<style scoped lang="less">
.dataBillTable{
  width: 100%;
  height: 100%;
  .titleCtn{
    height: 40px;
    line-height: 40px;
    margin-bottom: 10px;
    h1{
      font-size: 16px;
      color: #333;
      font-weight: bold;
    }
  }
  .tableDiv{
    width: 100%;
    height: calc(100% - 90px);
    margin-bottom: 10px;
  }
}
</style>

